<template>
	<mainUi ref="childUi" @reset="ResetScene"   />
</template>
<script setup>
import { onMounted, ref, watch, toRefs, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex'
import { gsap } from 'gsap'
import mainUi from '@/views/UI/index.vue'
import SceneManger from './js/SceneManger.js'
import flyToPath from './data/flyToPath.js'
const childUi = ref(null) // 与模板 ref 同名
const store = useStore()
const { sandboxReady, deviceListId } = toRefs(store.state)
const initPos = {
  cameraPos: [3.53, 52.54, 47.75],
  target: [2.95, -9.76, 4.65]
}
let currentClickArea = null
let currentClickDevice = null
let currentClick3Dlabel = null
let lock = true
const lockTimer = null
onMounted(() => {
  watch(
    sandboxReady,
    async ready => {
      if (ready) {
        window.sandbox.camera.position.set(...initPos.cameraPos)
        window.sandbox.controls.target.set(...initPos.target)
        // const axesHelper = new GC.AxesHelper(5)
        // axesHelper.position.set(0, 0.2, 0)
        // window.sandbox.scene.add(axesHelper)
        SceneManger.InitScene(DeviceClickcallBack, socketCallBack)
        SceneManger.Create3DLable(Click3DLable)
        // AddMouseEvent()

        // lockTimer = setTimeout(() => {
        //   initElements()
        //   setupUserActivityListeners()
        // }, window.START_DELAY)
        // let angle = 0
        // document.addEventListener('keydown', e => {
        //   if (e.key === 'u') {
        //     angle -= 1
        //     window.sandbox.rotateCameraAroundYAxis(-1)
        //   }
        //   if (e.key === 'i') {
        //     angle += 1
        //     window.sandbox.rotateCameraAroundYAxis(+1)
        //   }
        //   console.log('angle', angle)
        // })
      }
    },
    { immediate: true }
  )
  watch(() => deviceListId, () => {
    if (deviceListId.value) {
    //
      SceneManger.HighModel(deviceListId.value)
    } else {
      SceneManger.clearOutLine()
    }
  }, { deep: true })
})

// 点击3D面板
function Click3DLable (target, id, label) {
  if (currentClick3Dlabel) {
    currentClick3Dlabel.visible = true
  }
  currentClick3Dlabel = label
  currentClick3Dlabel.visible = false
  target.zoomToTween()

  // 同一个区域再次点击直接忽略
  if (currentClickArea?.AreaId === id) return

  // 业务刷新
  console.log('ididid', id)

  childUi.value.ChangeArea(id)

  SceneManger.focusAreaModel(id)
  currentClickDevice = null
}
// 点击设备
async function DeviceClickcallBack (target, item) {
  // 同一个区域再次点击直接忽略
  console.log('点击设备', item)
  store.commit('setDeviceListId', item.id)
}

function ResetCamera () {
  // 使用 GSAP 动画平滑过渡
  gsap.to(window.sandbox.camera.position, {
    x: initPos.cameraPos[0],
    y: initPos.cameraPos[1],
    z: initPos.cameraPos[2],
    duration: 1, // 动画时长（秒）
    ease: 'power2.inOut' // 缓动函数
  })
  // 使用 GSAP 动画平滑过渡
  gsap.to(window.sandbox.controls.target, {
    x: initPos.target[0],
    y: initPos.target[1],
    z: initPos.target[2],
    duration: 1, // 动画时长（秒）
    ease: 'power2.inOut' // 缓动函数
  })
}

function ResetSelect () {
  if (currentClickArea) {
    currentClickArea.clicktarget.visible = false
    currentClickArea = null
    currentClickDevice = null
  }
}

function ResetScene (isResetCamera = true) {
  store.commit('setCurrentRegionName', '')
  store.commit('setDeviceListId', '')
  isResetCamera && ResetCamera()
  ResetSelect()
  SceneManger.clearOutLine()
  SceneManger.ResetAllmodelMats()
  if (currentClick3Dlabel) {
    currentClick3Dlabel.visible = true
    currentClick3Dlabel = null
  }
  if (currentClickDevice) {
    currentClickDevice = null
  }
}

function socketCallBack (data) {
  console.log('WS', data)
  // 设备列表
  if (data.key === 'deviceStatus' && data.value?.length) {
    store.commit('setDeviceList', data.value)
  }
  // tudo 对接设备详情，报警汇总
  // store.commit('setInfoFuzzy', data) // 所有型架在线位置
  // store.commit('setAlarmListData', data) // 报警列表
  // store.commit('xxxxx', data) // 设备信息
}

// #region 自动巡检逻辑
let css3dElements = []
function initElements () {
  if (css3dElements.length === 0) {
    const list = document.querySelectorAll('.element')
    css3dElements = Array.from(list).sort((a, b) => {
      const na = parseInt(a.id.split('_')[1], 10)
      const nb = parseInt(b.id.split('_')[1], 10)
      return na - nb
    })
  }
}
const LastCallIndex = ref(-1)
let userActivityTimeout = null
let functionTimeout = null
const isPaused = ref(false)

// 监听用户操作事件
function setupUserActivityListeners () {
  const events = ['mousemove', 'mousedown', 'mouseup', 'wheel', 'DOMMouseScroll']
  events.forEach(event => {
    window.addEventListener(event, handleUserActivity, { passive: true })
  })

  lock && executeOperations(flyToPath)
}
// 用户操作处理
function handleUserActivity () {
  lock = false
  userActivityTimeout && clearTimeout(userActivityTimeout)

  // 如果有正在执行的操作且未暂停，则暂停当前操作
  if (LastCallIndex.value !== -1 && !isPaused.value) {
    isPaused.value = true

    const currentItem = flyToPath[LastCallIndex.value]
    console.log('currentItem', currentItem)

    if (currentItem.type === 'flyTo') {
      // console.log('暂停相机')
      window.sandbox.flyToStop()
    } else if (currentItem.type === 'function') {
      // console.log('暂停方法')
      store.commit('setIsReverse', false)
      functionTimeout && clearTimeout(functionTimeout)
      ResetScene(false)
    }
  }

  // 恢复操作-- 5秒
  userActivityTimeout = setTimeout(() => {
    if (isPaused.value) {
      isPaused.value = false

      // 从上次暂停的位置继续执行
      if (LastCallIndex.value !== -1 && LastCallIndex.value < flyToPath.length) {
        executeOperations(flyToPath.slice(LastCallIndex.value))
      }
    }
  }, window.ROAM_DELAY)
}

// 执行程序
async function executeOperations (operations) {
  for (const [index, item] of operations.entries()) {
    if (isPaused.value) {
      LastCallIndex.value = index
      return
    }
    // 更新最后执行位置
    LastCallIndex.value = index

    // 执行操作逻辑
    if (item.type === 'flyTo') {
      await window.sandbox.flyTo({
        position: item.position,
        target: item.target,
        duration: item.duration,
        stay: item.stay
      })
    } else if (item.type === 'function') {
      await new Promise((resolve) => {
        console.log('调用面板')
        store.commit('setIsReverse', !!item.isReverse)
        Enterpanel(item.function)

        functionTimeout = setTimeout(() => {
          console.log('清除面板')

          ResetScene(false)
          functionTimeout && clearTimeout(functionTimeout)
          resolve()
        }, window.WORKSTATION_DELAY)
      })
    }
  }

  // 循环播放：执行完成后重新开始
  if (!isPaused.value && LastCallIndex.value === operations.length - 1) {
    console.log('最后一次')

    LastCallIndex.value = -1
    executeOperations(flyToPath)
  }
}

document.addEventListener('keydown', e => {
  if (e.key === ' ') {
    if (lock) {
      clearTimeout(lockTimer)
      initElements()
      setupUserActivityListeners()
      lock = false
    } else {
      if (isPaused.value) {
        isPaused.value = false
        // 从上次暂停的位置继续执行
        if (LastCallIndex.value !== -1 && LastCallIndex.value < flyToPath.length) {
          executeOperations(flyToPath.slice(LastCallIndex.value))
        }
      }
    }
  }
})

function Enterpanel (AreaIdid) {
  const el = css3dElements.find(item => item.id.includes(AreaIdid))
  el.click()
  store.commit('setCurrentRegionName', AreaIdid)
}
// #endregion

onBeforeUnmount(() => {
  SceneManger.destroyModels()
})
</script>

<style lang="less"></style>
